// pages/library/index.js
import ImgListCell from '../../template/ImgListCell';
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    tabBarIndex:2,
    navigate: ['记者稿件', '来稿', '云媒号'],
    selectedIndex: 0,
    laigaoType: ['文章', '直播'],
    laigaoTypeIndex: 0,
    keyword: "",
    searchPlaceholder: "",
    page: 1,
    dataList: [],
    // 显示加载更多 loading
    hothidden: true,
    loadinghidden: true,
    isAddBtnShow: false,
    isTouchstart: false,
    isLongtap: false,
    isTouchmove: false,
    columnIndex: 0,
    columnID: 0,
    columnArray: [],
    columnNameArray: [],
    cyViewShow: false,
    cyTitle: "",
    cyID: 0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    Object.assign(this, ImgListCell);
    /**
     * 获取系统信息
     */
    wx.getSystemInfo({

      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    /**
     * 显示 loading
     */
    that.setData({
      loadinghidden: false
    });
    that.doLoadData();
  },
  onReady: function() {
    // 生命周期函数--监听页面初次渲染完成
    // 页面渲染完成
    var that = this;

    // 数据加载完成后 延迟隐藏loading
    setTimeout(function() {
      that.setData({
        loadinghidden: true
      })
    }, 500);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    //添加选中效果
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      var tabBar = wx.getStorageSync("tabBar");

      var tabBarIndex = that.data.tabBarIndex;
      for(var i=0;i<tabBar.length;i++){
        if(tabBar[i].pagePath.indexOf("library")>0){
          tabBarIndex=i;
          break;
        }
      }

      this.getTabBar().setData({
        selected: tabBarIndex, //这个数是，tabBar从左到右的下标，从0开始
        list: tabBar
      })
    }

    //获取用户信息
    http.ApiGet(apiUrl.UrlUserInfo, {}, function(res) {
      if (res.code == 1) {
        var user = res.data.userinfo;
        wx.setStorageSync("user", user);
        var tabBar = util.setTabBarData(res.data);

        if (user.is_reporter == 1) {
          that.setData({
            isAddBtnShow: true
          });
        }else{
          var user_role = wx.getStorageSync("user_role");
          if (user_role == "reporter") {
            that.setData({
              isAddBtnShow: true
            });
          }
        }

        if (typeof that.getTabBar === 'function' &&
          that.getTabBar()) {
          that.getTabBar().setData({
            selected: tabBarIndex,
            list: tabBar
          })
        }
      } else {
        wx.reLaunch({
          url: '../login/index'
        })
      }
    });
  },
  topNavTap: function(data) {
    var that = this;
    var selectedIndex = data.detail.selectedIndex;
    console.log("topNavTap:" + selectedIndex);
    that.setData({
      selectedIndex: selectedIndex,
      keyword: "",
      dataList: [],
      loadinghidden: false
    });
    that.doLoadData();
  },
  laigaoTypeChange: function(e) {
    this.setData({
      laigaoTypeIndex: e.detail.value,
      dataList: [],
      loadinghidden: false
    })
    this.doLoadData();
  },
  doLoadData: function() {
    var that = this;

    //默认记者稿件
    var url = apiUrl.UrlLibraryList;

    var parameter = {};
    parameter['page'] = 1;
    parameter['keyword'] = that.data.keyword;

    //来稿
    if (that.data.selectedIndex == 1) {
      url = apiUrl.UrlLaigaoList;
      parameter['type'] = that.data.laigaoTypeIndex + 1;
    }

    //云媒号
    if (that.data.selectedIndex == 2) {
      url = apiUrl.UrlYmhList;
    }

    http.ApiGet(url, parameter, function(res) {
      wx.stopPullDownRefresh() //停止下拉刷新
      if (res.code == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          newData = newData.map(function(item) {
            item.ptime = item.create_time_text + "  采用:" + item.used_count+"次"; // util.getDateDiff(item.ptime + '000');
            // if (item.user_name != null) {
            //   item.user_name = item.user_name.substring(0, 8);
            // } else {
            //   item.user_name = "";
            // }
            item.autor = item.user_name;
            if (item.images.length > 0) {
              item.thumb = item.images;
            }
            if (that.data.selectedIndex == 1) {
              if (item.type == 1) {
                item.label = "稿件";
              } else {
                item.label = "直播";
              }
            }

            return item;
          })
        } else {
          newData = [];
          // wx.showModal({
          //   title: "暂无数据！"
          // });
        }
        that.setData({
          page: 1,
          hothidden: false,
          loadinghidden: true,
          dataList: newData
        });
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.doLoadData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;

    // 加载更多 loading
    that.setData({
      hothidden: true
    })

    var page = that.data.page + 1;
    // 获取当前现有数据进行保存
    var list = that.data.dataList;

    //默认记者稿件
    var url = apiUrl.UrlLibraryList;

    var parameter = {};
    parameter['page'] = page;
    parameter['keyword'] = that.data.keyword;

    //来稿
    if (that.data.selectedIndex == 1) {
      url = apiUrl.UrlLaigaoList;
      parameter['type'] = that.data.laigaoTypeIndex + 1;
    }
    //云媒号
    if (that.data.selectedIndex == 2) {
      url = apiUrl.UrlYmhList;
    }

    http.ApiGet(url, parameter, function(res) {

      if (res.code == 1) {
        var newData = res.data;
        if (newData.length > 0) {

          that.setData({
            page: page,
            hothidden: false,
            dataList: list.concat(newData.map(function(item) {
              item.ptime = item.create_time_text + " | 采:" + item.used_count;
              item.autor = item.user_name;
              if (item.images.length > 0) {
                item.thumb = item.images;
              }
              if (that.data.selectedIndex != 2) {
                if (item.type == 1) {
                  item.label = "稿件";
                } else {
                  item.label = "直播";
                }
              }

              return item;
            }))
          });
        } else {
          that.setData({
            hothidden: false
          })
        }
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  searchContentInput: function(e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  searchSubmit: function() {
    var that = this;
    var keyword = that.data.keyword;
    // if (keyword != "") {
    //   console.log(keyword);
    //   that.doLoadData();
    // } else {
    //   wx.showModal({
    //     title: "请输入搜索关键字！"
    //   });
    // }
    that.doLoadData();
  },
  addBtnTap: function() {
    var that = this;
    wx.navigateTo({
      url: '../document/submit'
    })
  },
  //按下事件开始  
  doTouchstart: function(e) {
    let that = this;

    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];

    that.setData({
      isTouchstart: true,
      isLongtap: false
    })

    setTimeout(function() {
      if (that.data.isTouchstart && !that.data.isTouchmove) {
        that.setData({
          isLongtap: true
        })

        console.log("到时间了,是长按");

        if (that.data.isAddBtnShow){
          return;
        }

        that.setData({
          cyViewShow: true,
          cyTitle: item.title,
          cyID: item.id,
        });
        that.loadColumnData();
      }
    }, 500);
  },
  loadColumnData: function() {
    var that = this;
    var parameter = {};
    parameter['all'] = 0;
    //获取数据
    http.ApiGet(apiUrl.UrlColumnTree, parameter, function(res) {
      wx.stopPullDownRefresh() //停止下拉刷新
      if (res.code == 1) {
        var newData = res.data;
        if (newData.length > 0) {
          var columnName = [];
          var columnID = newData[0].id;

          newData.map(function(item) {
            columnName.push(item.text);
          });
          that.setData({
            columnID: columnID,
            columnArray: newData,
            columnNameArray: columnName
          });
        }
      }
    });
  },
  columnPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var columnArray = this.data.columnArray;
    this.setData({
      columnIndex: e.detail.value,
      columnID: columnArray[e.detail.value].id
    })
    this.doLoadData();
  },
  columnBtnTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var columnArray = this.data.columnArray;
    this.setData({
      columnIndex: index,
      columnID: columnArray[index].id
    })
  },
  //直接采用
  okBtnTap: function() {
    var that = this;
    that.cancelBtnTap();

    if (that.data.columnID == 0) {
      wx.showModal({
        title: "请选择栏目"
      });
      return;
    }

    var formData = {};

    formData['column_id'] = that.data.columnID;

    var url = apiUrl.UrlDocumentUse;

    //来稿
    if (that.data.selectedIndex == 1) {
      url = apiUrl.UrlLaigaoUse;
      //文章
      if (that.data.laigaoTypeIndex == 0) {
        formData['document_id'] = that.data.cyID;
        //直播
      } else {
        formData['live_id'] = that.data.cyID;
      }
      //云媒号
    } else if (that.data.selectedIndex == 2) {
      url = apiUrl.UrlYmhUse;
      formData['ymh_aid'] = that.data.cyID;
      //记者稿件
    } else {
      formData['document_id'] = that.data.cyID;
    }

    http.ApiPost(url, formData, function(res) {
      if (res.code == 1) {
        console.log(res.msg);
        wx.showModal({
          title: "采用成功"
        });
      } else {
        wx.showModal({
          title: res.msg
        });
        console.log(res.msg);
      }
    });
  },
  editBtnTap: function() {
    var that = this;
    that.cancelBtnTap();
    if (that.data.columnID == 0) {
      wx.showModal({
        title: "请选择栏目"
      });
      return;
    }
    //来稿
    if (that.data.selectedIndex == 1) {
      //文章
      if (that.data.laigaoTypeIndex == 0) {
        wx.navigateTo({
          url: '../news/submit?lgid=' + that.data.cyID + '&cid=' + that.data.columnID
        });
      //直播
      } else {
        wx.showModal({
          title: "暂不支持"
        });
      }
    //云媒号
    } else if (that.data.selectedIndex == 2) {
      wx.navigateTo({
        url: '../news/submit?ymhid=' + that.data.cyID + '&cid=' + that.data.columnID
      });
    //记者稿件
    } else {
      wx.navigateTo({
        url: '../news/submit?did=' + that.data.cyID + '&cid=' + that.data.columnID
      });
    }
  },
  cancelBtnTap: function() {
    var that = this;
    that.setData({
      cyViewShow: false
    });
  },
  //按下事件结束  
  doTouchend: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];
    that.setData({
      isTouchstart: false
    })

    if (!that.data.isLongtap && !that.data.isTouchmove) {
      console.log("点击 " + item.id);

      if (that.data.selectedIndex != 0) {
        var link = item.link;
        if (link.indexOf("v.sogx.cn") > 0 || link.indexOf("laigao.longsunhd.com") > 0 || link.indexOf("www.sogx.cn") > 0) {
          link = link.replace("http:", "https:");
          link = link.replace(":8080", "");
          wx.navigateTo({
            url: '../webview/index?url=' + link
          })
        }
      } else {
        if (item.type == 1) {
          wx.navigateTo({
            url: '../document/detail?id=' + item.id
          })
        } else {
          wx.showModal({
            title: "暂不支持"
          });
        }
      }

    }
    that.setData({
      isTouchmove: false
    });
  },
  doTouchmove: function(e) {
    let that = this;
    that.setData({
      isTouchmove: true
    })
    console.log("滑动");
  },
  listCellTap: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var item = that.data.dataList[index];
    console.log(item.id);

    if (that.data.selectedIndex != 0) {
      var link = item.link;
      if (link.indexOf("v.sogx.cn") > 0 || link.indexOf("laigao.longsunhd.com") > 0 || link.indexOf("www.sogx.cn") > 0) {
        link = link.replace("http:", "https:");
        link = link.replace(":8080", "");
        wx.navigateTo({
          url: '../webview/index?url=' + link
        })
      }
    } else {
      if (item.type == 1) {
        wx.navigateTo({
          url: '../document/detail?id=' + item.id
        })
      } else {
        wx.showModal({
          title: "暂不支持"
        });
      }
    }
  },
})